<?php

/**
* Send query to database and get results
*/
class BabiliDBCommunicator {

	/**
	  * Id of the db connexion
	 */
	private $host = 'localhost';
	private $user = 'root';
	private $pass = '';
	private $dbtype = 'mysql';
	private $dbname = 'babili2';
	
	//We use one pdo session for all our queries
	private $pdo;
	
	/**
	 * Init the communication with the db
	 */
	public function __construct(){
		$dsn = $this->dbtype . ':dbname=' . $this->dbname . ';host=' . $this->host;
		$this->pdo = new PDO($dsn, $this->user, $this->pass);
	}
	
	/**
	 * Execute select query
	 * @param $query
	 * @param $query_args array of value to replace in the query [optionnal]
	 * 					 example : $query_args = array(':productid' => 2), we search in $query all string ":productid" and replace by 2
	 * @return $results array of results if any
	 * 					if any errors in query, return false
	 */
	public function select($query, $query_args = array()){
		
		$query_object = $this->pdo->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
		
		if($query_object->execute($query_args)){
			//get result
			$results = $query_object->fetchAll();
			return $results;
		}
		else{
			var_dump($this->pdo->errorInfo());
			return false;
		}
	}
	
	/**
	 * Update query (insert, update, delete)
	 * @param $query
	 * @param $query_args array of value to replace in the query [optionnal]
	 * 					 example : $query_args = array(':productid' => 2), we search in $query all string ":productid" and replace by 2
	 * @return bool (true if the query is ok)
	 */
	public function update($query, $query_args = array()){
		
		$query_object = $this->pdo->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
		
		if($query_object->execute($query_args)){
			return true;
		}
		else{
			var_dump($this->pdo->errorInfo());
			return false;
		}
	}
	
	
	/**
	 * Function that give the last insert id
	 */
	public function last_id(){
		return $this->pdo->lastInsertId();
	}
	
	
}